package com.leetcode.p100;

import com.bean.TreeNode;
import com.utils.TreeUtils;

import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * 二叉树的后续遍历
 * <p>
 * 前序遍历的  反转  ，主要是addFirst和再遍历右子树
 */
public class Test145_stack {

    public List<Integer> postorderTraversal(TreeNode root) {
        LinkedList<Integer> res = new LinkedList<>();
        Deque<TreeNode> stack = new LinkedList<>();

        while (!stack.isEmpty() || root != null) {
            while (root != null) {
                res.addFirst(root.val);
                stack.push(root);
                root = root.right;
            }

            if (!stack.isEmpty()) {
                root = stack.pop();
                root = root.left;
            }
        }

        return res;
    }

    public static void main(String[] args) {
        TreeNode root = TreeUtils.buildTree4();
        TreeUtils.showTree(root);

        Test145_stack test = new Test145_stack();
        List result = test.postorderTraversal(root);
        System.out.println(result);
    }

}
